package at.fhooe.engine.scenegraph;

import java.awt.Graphics2D;
import java.util.HashMap;

public class SceneNodeManager {

	private SceneNode m_rootSceneNode;
	private HashMap<String, SceneNode> m_allSceneNodes;
	
	public SceneNodeManager() {
		setRootSceneNode(new SceneNode("rootSceneNode"));
		m_allSceneNodes = new HashMap<String, SceneNode>();
	}
	
	public synchronized void drawNodes(Graphics2D graphics) {
		m_rootSceneNode.drawNode(graphics);
	}
	
	public void setRootSceneNode(SceneNode sceneNode) {
		m_rootSceneNode = sceneNode;
	}
	
	public SceneNode getRootSceneNode() {
		return m_rootSceneNode;
	}
	
	public SceneNode getSceneNode(String name) {
		return m_allSceneNodes.get(name);
	}
	
	public SceneNode createSceneNode(String name) {
		if (m_allSceneNodes.containsKey(name))
			return null;
		
		SceneNode newNode = new SceneNode(name);
		m_rootSceneNode.addChild(newNode);	// automatically link a new node with the root node
		m_allSceneNodes.put(name, newNode);
		
		return newNode;
	}
	
	public boolean destroySceneNode(String name) {
		return destroySceneNode(m_allSceneNodes.get(name));
	}
	
	public boolean destroySceneNode(SceneNode destroyNode) {
		if (destroyNode == null || !m_allSceneNodes.containsKey(destroyNode.getName()))
			return false;
		
		SceneNode parentNode = destroyNode.getParent();
		if (parentNode != null)
			parentNode.removeChild(destroyNode);
		
		m_allSceneNodes.remove(destroyNode);
		
		return true;
	}
	
	public void destroyAllSceneNodes() {
		m_rootSceneNode.removeAllChildren();
		
		m_allSceneNodes = new HashMap<String, SceneNode>();
	}
	
}
